package com.demo.util;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;

public class JsonUtil {
  private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

  public static String toJson(Object obj) {
    if (obj == null) return "null";

    if (obj instanceof Collection) {
      return collectionToJson((Collection<?>) obj);
    } else if (obj instanceof String) {
      return "\"" + escapeJson((String) obj) + "\"";
    } else if (obj instanceof Number || obj instanceof Boolean) {
      return obj.toString();
    } else if (obj instanceof Date) {
      return "\"" + DATE_FORMAT.format((Date) obj) + "\"";
    } else {
      return objectToJson(obj);
    }
  }

  private static String objectToJson(Object obj) {
    StringBuilder sb = new StringBuilder("{");
    Field[] fields = obj.getClass().getDeclaredFields();
    boolean firstField = true;

    for (Field field : fields) {
      field.setAccessible(true);
      try {
        Object value = field.get(obj);
        if (value == null) continue;

        if (!firstField) {
          sb.append(",");
        }
        firstField = false;

        sb.append("\"").append(field.getName()).append("\":");

        if (value instanceof String || value instanceof Date) {
          sb.append("\"").append(escapeJson(value.toString())).append("\"");
        } else if (value instanceof Number || value instanceof Boolean) {
          sb.append(value);
        } else {
          sb.append(toJson(value));
        }

      } catch (IllegalAccessException e) {
        // 忽略无法访问的字段
      }
    }

    return sb.append("}").toString();
  }

  private static String collectionToJson(Collection<?> collection) {
    StringBuilder sb = new StringBuilder("[");
    boolean firstElement = true;

    for (Object item : collection) {
      if (!firstElement) {
        sb.append(",");
      }
      firstElement = false;
      sb.append(toJson(item));
    }

    return sb.append("]").toString();
  }

  private static String escapeJson(String input) {
    if (input == null) return "";
    return input.replace("\\", "\\\\")
        .replace("\"", "\\\"")
        .replace("\b", "\\b")
        .replace("\f", "\\f")
        .replace("\n", "\\n")
        .replace("\r", "\\r")
        .replace("\t", "\\t");
  }
}